﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IGIS.Core;
using AjaxControlToolkit;
using System.IO;
using OSGeo.MapGuide;

namespace IGIS.Controls
{
    public partial class UploaderControl : System.Web.UI.UserControl
    {
        
        private bool _activated;
        private ModuleConfig _config;
        private int _featureId;
        private string _featureSource;
        private HtzMgHelper _helper;
        //protected Button btnUpload;
        //protected AsyncFileUpload fileAsyncUpload;
        ////private  Repeater FileList;
        //protected Label lblControlError;
        //protected Panel panelControlError;
        //protected TextBox txtDescription;
        //protected Panel UploaderPanel;
        //protected ScriptManagerProxy uploaderScriptManagerProxy;

        public event EventHandler<ErrorEventArgs> ControlError;

        public void Activate(HtzMgHelper helper, ModuleConfig config)
        {
            this._helper = helper;
            this._config = config;
            this._activated = true;
            
        }
        
        private void BindFileList()
        {
            this.FileList.DataSource = HtzFile.GetFiles(this.ViewState["ProjectName"].ToString(), this._featureSource, (long)this._featureId);
            this.FileList.DataBind();
        }

        protected void OnFileListCommand(object source, RepeaterCommandEventArgs e)
        {
            string _CommandName = e.CommandName;
            if (_CommandName != null)
            {
                long longcomand = 0;
                long.TryParse(e.CommandArgument.ToString(), out longcomand);
                if (!(_CommandName == "Edit"))
                {
                    if (_CommandName == "Update")
                    {
                        string txt = ((TextBox)e.Item.FindControl("txtDescriptionUpdate")).Text;
                        HtzFileManager.UpdateFile(this.ViewState["ProjectName"].ToString(), longcomand, txt);
                        this.BindFileList();
                    }
                    else if (_CommandName == "Delete")
                    {
                        

                        HtzFileManager.DeleteFile( this.ViewState["ProjectName"].ToString(), this._featureSource, (long)this._featureId, longcomand);
                        this.BindFileList();
                    }
                    else if (_CommandName == "Cancel")
                    {
                        SwitchMode(e.Item, false);
                    }
                }
                else
                {
                    SwitchMode(e.Item, true);
                }
            }
        }
        public string IdField { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _activated=true;
                if (!base.IsPostBack)
                {
                    this.ViewState.Add("SESSION", base.Request["SESSION"]);
                    this.ViewState.Add("ProjectName", base.Request["ProjectName"]);
                    this.ViewState.Add("MAPNAME", base.Request["MAPNAME"]);
                    
                    if (ViewState["IdField"] == null )
                    {
                        this.ViewState.Add("IdField", string.IsNullOrEmpty(IdField) ? "FeatId" : IdField);
                    }
                   
                }
                if (!(this._activated ))
                {
                    this.lblControlError.Text = "אין אפשרות לבצע הפעולה לשכבה זו, אנא פנה למנהל מערכת";

                    //ErrorStrings.LayerNotSupported;
                    this.panelControlError.Visible = true;
                    this.UploaderPanel.Visible = false;
                }
                else
                {
                    //this.ViewState.Add("ProjectName", base.Request["ProjectName"]);
                    this._helper = new HtzMgHelper(this.ViewState["SESSION"].ToString(), this.ViewState["MAPNAME"].ToString(), null);
                    this._featureSource = this._helper.Selection.GetLayers().GetItem(0).GetFeatureSourceId();
                    try
                    {
                        this._featureId = HtzFileManager.GetUidFromSelection(this._helper, this.ViewState["IdField"].ToString());
                        this.UploaderPanel.Visible = true;
                    }
                    catch (MgException exx)
                    {
                        this.lblControlError.Text = exx.GetExceptionMessage();// "אין אפשרות לבצע הפעולה לשכבה זו, אנא פנה למנהל מערכת";//ErrorStrings.LayerNotSupported;
                        this.panelControlError.Visible = true;
                        this.UploaderPanel.Visible = false;
                    }
                    if (!base.IsPostBack)
                    {
                        this.BindFileList();
                    }
                }
            }
            catch (MgException ex)
            {
                this.ControlError(this, new ErrorEventArgs(ex));
            }
            catch (Exception ex)
            {
                this.ControlError(this, new ErrorEventArgs(ex));
            }
        }

        private static void SwitchMode(Control item, bool editMode)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            Label lbl = (Label)item.FindControl("lblDescription");
            lbl.Visible = !editMode;
            Panel txt = (Panel)item.FindControl("FileEditPanel");
            txt.Visible = editMode;
            Panel cmdPanel = (Panel)item.FindControl("CommandPanel");
            cmdPanel.Visible = !editMode;
        }

        protected void UploadFile(object sender, EventArgs e)
        {
            if ((this.fileAsyncUpload.FileContent == null) || (this.fileAsyncUpload.FileContent.Length == 0L))
            {
                this.ControlError(this, new ErrorEventArgs(new Exception("עליך לבחור קובץ.")));
                //this.ControlError(this, new ErrorEventArgs("עליך לבחור קובץ."));
                /*ErrorStrings.NoFileToUpload*/
            }
            else
            {
                string descr = HttpUtility.HtmlEncode(this.txtDescription.Text);
                HtzFileManager.AddFile(this.fileAsyncUpload.FileContent, this.ViewState["ProjectName"].ToString(), this._helper.Map.GetName(), this._featureSource, (long)this._featureId, this.fileAsyncUpload.FileName, descr);
                this.txtDescription.Text = "";
                this.BindFileList();
            }
        }
    }
}